<?php

namespace humhub\modules\api\controllers;

use Yii;
use humhub\components\Controller;
use humhub\modules\notification\models\Notification;
use humhub\modules\notification\models\forms\FilterForm;

use yii\filters\auth\CompositeAuth;
use yii\filters\auth\HttpBearerAuth;

/**
 * 获取我的消息通知
 */
class NotificationController extends Base4Controller
{

    /**
     * @inheritdoc
     */
    public function behaviors(){
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => CompositeAuth::className(),
            'authMethods' => [
                //QueryParamAuth::className(),
                HttpBearerAuth::className(),
            ],
        ];

        $behaviors['acl'] = [
            'class' => \humhub\components\behaviors\AccessControl::className(),
        ];

        return $behaviors;
    }

    /**
     * 阅读通知,并获取通知处理类型
     *
     * GET /api/notification/entry?id=[id]
     *
     * get.id Entry的ID
     *
     * @return array module通知所属类型, guid对应类型的guid
     */
    public function actionEntry(){
        $notificationModel = Notification::findOne(['id' => Yii::$app->request->get('id'), 'user_id' => Yii::$app->user->id]);

        if ($notificationModel === null) {
            throw new \yii\web\HttpException(404, 'Could not find requested notification!');
        }

        $n = $notificationModel->getClass();
        $n->markAsSeen(); //系统自己的消息处理
        //$n->record->seen = 1;
        //$n->record->save(); //改为只处理单条信息

        $guid = '';
        //<!-- show user -->
        if ($n->originator !== null){
            $guid = $n->originator->guid;
        }
        //<!-- show space -->
        if ($n->space !== null){
            $guid = $n->space->guid;
        }

        return array(
            'module' => $n->moduleId,
            'guid' => $guid,
        );
        //return $notification->getUrl();
    }

    /**
     * 获取最新的几条消息通知
     *
     * GET /api/notification
     *
     * @return array lastEntryId:最后一条消息的EntryId, counter:返回的通知数, datas数据(entryid:EntryId, isNew:true未读消息, img用户或Space头像, content内容, times时间, module通知所属类型, guid对应类型的guid)
     */
    public function actionIndex(){
        $query = Notification::findGrouped();
        //$query = Notification::find();
        //$query->orderBy(['created_at' => SORT_DESC]);

        $maxId = (int) Yii::$app->request->get('from', 0);
        if ($maxId != 0) {
            $query->andWhere(['<', 'id', $maxId]);
        }
        $query->andWhere(['user_id' => Yii::$app->user->id]);
        $query->andWhere(['seen' => 0]);
        $query->limit(1);

        $output = "";
        $datas = [];

        $notifications = $query->all();
        //return $query->createCommand()->getRawSql();exit;
        $lastEntryId = 0;
        foreach ($notifications as $notification) {
            $lastEntryId = $notification->id;
            //$output .= $notification->getClass()->render();
            $n = $notification->getClass();

            $d['module'] = $n->moduleId;
            //$d['url'] = \yii\helpers\Url::to(['/notification/entry', 'id' => $n->record->id], true);
            $d['entryid'] = $n->record->id;
            $d['isNew'] = ($n->record->seen != 1);

            //<!-- show user image -->
            if ($n->originator !== null){
                $d['img'] = $n->originator->getProfileImage()->getUrl();
                $d['guid'] = $n->originator->guid;
                $d['displayname'] = $n->originator->displayName;
            }
            //<!-- show space image -->
            if ($n->space !== null){
                $d['img'] = $n->space->getProfileImage()->getUrl();
                $d['guid'] = $n->space->guid;
                $d['displayname'] = $n->space->displayName;
            }

            //BaseNotification->SocialActivity->Viewable
            $asHtml = strip_tags($n->getAsHtml());
            $d['content'] = $asHtml;
            $d['times'] = $n->record->created_at;

            $datas[] = $d;
        }

        return [
            //'datas' => $output,
            'datas' => $datas,
            'lastEntryId' => $lastEntryId,
            'counter' => count($notifications)
        ];
    }

    /**
     * 获取所有的消息通知 新增num 未读消息数量
     *
     * GET /api/notification/all?FilterForm[moduleFilter][]=[筛选]&FilterForm[moduleFilter][]=[筛选]
     *
     * get.FilterForm[moduleFilter][] = 当需要筛选通知时传值,可选值:[Space, 用户, Comment, Content, other]
     *
     * @return array lastEntryId:最后一条消息的EntryId, counter:返回的通知数, datas数据(entryid:EntryId, isNew:true未读消息, img用户或Space头像,title用户简介, content内容, times时间, module通知所属类型, guid对应类型的guid)
     */
    public function actionAll(){
        $pageSize = 10;
        $session = Yii::$app->session;
        $notifications = [];

        $filterForm = new FilterForm();
        $filterForm->initFilter();
        $filterForm->load(Yii::$app->request->get());

        $query = Notification::findGrouped();
        //$query = Notification::find();
        //$query->orderBy(['created_at' => SORT_DESC]);

        $query->andWhere(['user_id' => Yii::$app->user->id]);

        if ($filterForm->isExcludeFilter()) { //default
            $query->andFilterWhere(['not in', 'class', $filterForm->getExcludeClassFilter()]);
        } else if ($filterForm->isActive()) { //has FilterForm
            $query->andFilterWhere(['in', 'class', $filterForm->getIncludeClassFilter()]);
        } else {
            return [];
            return $this->render('index', [
                        'notificationEntries' => [],
                        'filterForm' => $filterForm,
                        'pagination' => null,
                        'notifications' => $notifications
            ]);
        }

        $countQuery = clone $query;
        $pagination = new \yii\data\Pagination(['totalCount' => $countQuery->count(), 'pageSize' => $pageSize]);

        //Reset pagegination after new filter set
        if (Yii::$app->request->post()) {
            $pagination->setPage(0);
        }

        $query->offset($pagination->offset)->limit($pagination->limit);

        //foreach ($query->all() as $notificationRecord) {
        //    $notifications[] = $notificationRecord->getClass();
        //}
        $datas = [];
        $num=0;
        $lastEntryId = '';
        foreach ($query->all() as $notification) {
            $lastEntryId = $notification->id;
            //$output .= $notification->getClass()->render();
            $n = $notification->getClass();

            if ($n->record->seen != 1) $num +=1;

            $d['module'] = $n->moduleId;
            //$d['url'] = \yii\helpers\Url::to(['/notification/entry', 'id' => $n->record->id], true);
            $d['entryid'] = $n->record->id;
            $d['isNew'] = ($n->record->seen != 1);
            $d['title'] =null;

            //<!-- show user image -->
            if ($n->originator !== null){
                $d['img'] = $n->originator->getProfileImage()->getUrl();
                $d['guid'] = $n->originator->guid;
                $d['title']       = $n->originator->profile->title;
                $d['displayname'] = $n->originator->displayName;
            }
//            <!-- show space image -->
//            if ($n->space !== null){
//                $d['img'] = $n->space->getProfileImage()->getUrl();
//                $d['guid'] = $n->space->guid;
//                $d['is_space'] = 1;
//                $d['displayname'] = $n->space->displayName;
//            }

            //BaseNotification->SocialActivity->Viewable
            $asHtml = strip_tags($n->getAsHtml());
            $d['content'] = $asHtml;
            $d['times'] = $n->record->created_at;

            $datas[] = $d;
        }

        return [
            //'datas' => $output,
            'datas' => $datas,
            'num'  =>$num,
            'lastEntryId' => $lastEntryId,
            'counter' => count($notifications)
        ];
        //return array(
        //    'notifications' => $notifications,
        //    'filterForm' => $filterForm,
        //    'pagination' => $pagination
        //);
    }

    /**
     * 获取新通知的数量
     *
     * GET /api/notification/get-update
     *
     * @return array newNotifications:新消息数量
     */
    public function actionGetUpdate(){
        Yii::$app->response->format = 'json';
        return $this->getUpdates();
    }
    public static function getUpdates(){
        $user = Yii::$app->user->getIdentity();

        $query = Notification::findGrouped()
                ->andWhere(['seen' => 0])
                ->orWhere(['IS', 'seen', new \yii\db\Expression('NULL')])
                ->andWhere(['user_id' => $user->id]);

        $update['newNotifications'] = $query->count();
        $query->andWhere(['desktop_notified' => 0]);

        $update['notifications'] = array();
        /*
        foreach ($query->all() as $notification) {
            if (Yii::$app->getModule('notification')->settings->user()->get("enable_html5_desktop_notifications", Yii::$app->getModule('notification')->settings->get('enable_html5_desktop_notifications'))) {
                $update['notifications'][] = $notification->getClass()->render(BaseNotification::OUTPUT_TEXT);
            }
            $notification->desktop_notified = 1;
            $notification->update();
        }
         */

        return $update;
    }

    /**
     * 批量处理所有新消息为:已读
     *
     * GET /api/notification/mark-as-seen
     *
     * @return array count:处理的数量
     */
    public function actionMarkAsSeen(){
        $count = Notification::updateAll(['seen' => 1], ['user_id' => Yii::$app->user->id]);
        return [
            'success' => true,
            'count' => $count
        ];
    }
}
